package org.dreamfly.core.action;

import org.apache.struts2.ServletActionContext;
import org.dreamfly.core.bean.RemoteServiceInfo;
import org.dreamfly.core.bean.ResultSetPool;
import org.dreamfly.core.bean.SzPicture;
import org.dreamfly.core.page.PageInfo;
import org.dreamfly.core.page.PageResultSet;
import org.dreamfly.core.remote.ServiceRepository;
import org.dreamfly.core.remote.exception.ServiceException;
import org.dreamfly.core.service.PictureService;
import org.dreamfly.core.service.PictureTypeService;
import org.dreamfly.core.util.MakeTypeIdList;
import org.dreamfly.core.util.PowerComparator;
import org.dreamfly.core.util.UrlGetter;
import org.dreamfly.core.util.XMLReader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PictureAction extends BaseAction {
    private String temp;
    private List<Long> pictureIds;
    private List<SzPicture> szPictures = new ArrayList<SzPicture>(0);
    //保存包含结果集和分页信息的数据集
    private PageResultSet<SzPicture> resultSet;
    private SzPicture picture;
    private ResultSetPool resultSetPool;
    private List<SzPicture> tempList;
    private PictureService pictureService;
    private Long pictureTypeId;
    private PictureTypeService pictureTypeService;
    private List<Long> szTypeIds;
    private List<Long> deleteIds;
    private String fileName;
    private String title;
    private String actionName;
    private Long id;
    private String server;
    private String note;
    private String isAdmin;
    private String searchId;
    private String clientPage = "1";
    private BootUpRegister bootUpRegister;
    private ServiceRepository serviceRepository;
    private PictureService pictureHessianProxy;
    public static final String uploadFolder = "/upload/";
    private UrlGetter urlGetter;
    private FileDownloadAction fileDownloadAction;
    /**
     * 分页参数
     * pageSize 每页的大小
     * page     显示的页码
     */
    private Long pageSize = 15L;
    private Long page = 1L;
    private SzPicture object;

    /**
     * 添加图片信息
     *
     * @return
     * @throws java.io.IOException
     */
    public String addPictureInfo() throws IOException {
        SzPicture temp = new SzPicture();
        temp.setServer(server);
        temp.setId(id);
        temp.setTitle(title);
        temp.setNote(note);
        pictureService.addPicInfo(temp);
        getResponse().getWriter().print("success");
        return null;
    }


    /**
     * 按关键字搜索指定类型的图片
     *
     * @return success
     */
    public String searchPictureByType() {
        if (picture == null) {
            picture = new SzPicture();
            picture.setTitle("%");
        }
        if ("".equals(picture.getTitle())){
            picture.setTitle("%");
        }
        /*try {
            picture.setTitle(new String(picture.getTitle().getBytes("ISO-8859-1"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }*/
        if (null == isAdmin) {
            resultSet = pictureService.normalSearchByType(szTypeIds, picture, null, pageSize, page);
            resultSet.setActionName("pictureNameSearch");
        } else {
            resultSet = pictureService.normalSearchByType(szTypeIds, picture, server, pageSize, page);
            resultSet.setActionName("bgPicture");
        }
        resultSet.setType("Picture");
        if (resultSet.getList() == null) {
            return INPUT;
        }
        resultSet.setKeyWords(picture.getTitle());

        resultSet.setIdList(MakeTypeIdList.combine(szTypeIds));
        return SUCCESS;
    }

    /**
     * 基于内容搜索指定类型图片
     *
     * @return success
     */
    public String contentSearchByType() {
        szTypeIds = MakeTypeIdList.divide(temp);
        resultSet = new PageResultSet<SzPicture>();
        Comparator comparator = new PowerComparator();
        //图片地址
        String pictureDir = uploadFolder + fileName;
        PageResultSet<SzPicture> finalResultSet;
        List<RemoteServiceInfo> infoList = XMLReader.readServerInfo(ServletActionContext.getServletContext().getRealPath("WEB-INF/picture.xml"));
        int serviceNum = infoList.size();
        //判断是不是第一次查询
        if (searchId == null) {
            searchId = String.valueOf(Math.random());
            if (szTypeIds != null && 0 != szTypeIds.size()) {
                tempList = pictureService.contentSearchByType(szTypeIds, pictureDir, pageSize, page);
            } else {
                tempList = pictureService.contentSearchByType(null, pictureDir, pageSize, page);
            }
            if (tempList == null) {
                tempList = new ArrayList<SzPicture>();
            }
            /**
             * 远程service
             */
            //远程服务和本地服务的数量和
            Long maxCount = pictureService.findCount(pictureDir, szTypeIds); //最多的记录数
            Long totalRow = pictureService.findCount(pictureDir, szTypeIds);
            /**
             * 初始化List
             */
            List<SzPicture> list;
            for (int i = 0; i < serviceNum; i++) {
                try {
                    pictureHessianProxy = (PictureService) serviceRepository.getService(PictureService.class, "picture_" + String.valueOf(i));
                } catch (ServiceException e) {
                    e.printStackTrace();
                    bootUpRegister.initService();
                    try {
                        pictureHessianProxy = (PictureService) serviceRepository.getService(PictureService.class, "picture_" + String.valueOf(i));
                    } catch (ServiceException e1) {
                        e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }
                if (null != szTypeIds && 0 != szTypeIds.size()) {
                    list = pictureHessianProxy.contentSearchByType(szTypeIds, pictureDir, pageSize, page);
                } else {
                    list = pictureHessianProxy.contentSearchByType(null, pictureDir, pageSize, page);
                }
                if (list != null) {
                    tempList.addAll(list);
                    if (pictureHessianProxy.findCount(pictureDir, szTypeIds) > maxCount) {
                        maxCount = pictureHessianProxy.findCount(pictureDir, szTypeIds);
                    }
                    totalRow += pictureHessianProxy.findCount(pictureDir, szTypeIds);
                }
                list = null;
                //serviceNum++;
            }

            Collections.sort(tempList, comparator);
            finalResultSet = new PageResultSet<SzPicture>();
            finalResultSet.setList(tempList);

            /**
             * 初始化PageInfo
             */
            PageInfo pageInfo = new PageInfo(totalRow, pageSize);
            pageInfo.setClientPage(Long.parseLong(clientPage));
            pageInfo.setMaxQueryTimes(maxCount % pageSize == 0 ? maxCount / pageSize : maxCount / pageSize + 1);
            finalResultSet.setPageInfo(pageInfo);
            resultSetPool.createResultSet(request.getSession().getId(), searchId, finalResultSet);
        }
        //判断需不需要再查询
        else {
            finalResultSet = resultSetPool.getResultSet(request.getSession().getId(), searchId);
            finalResultSet.getPageInfo().setClientPage(Long.parseLong(clientPage));
            if (finalResultSet.needQueryDB()) {
                while (finalResultSet.needQueryDB()) {
                    PageInfo pageInfo = resultSetPool.getResultSet(request.getSession().getId(), searchId).getPageInfo();
                    if (pageInfo.getMaxQueryTimes() == pageInfo.getQueryTime()) {
                        break;
                    }
                    Long page = pageInfo.getQueryTime() + 1L;
                    if (szTypeIds != null) {
                        tempList = pictureService.contentSearchByType(szTypeIds, pictureDir, pageSize, page);
                    } else {
                        tempList = pictureService.contentSearchByType(null, pictureDir, pageSize, page);
                    }
                    if (tempList == null) {
                        tempList = new ArrayList<SzPicture>();
                    }
                    resultSetPool.getResultSet(request.getSession().getId(), searchId).getList().addAll(tempList);

                    /**
                     * 远程service
                     */
                    /*List<RemoteServiceInfo> infoList = XMLReader.readServerInfo(ServletActionContext.getServletContext().getRealPath("WEB-INF/picture.xml"));
                     int serviceNum = 1; //远程服务和本地服务的数量和*/

                    /**
                     * 增加List
                     */
                    for (int i = 0; i < serviceNum; i++) {
                        /*Class serviceClass = PictureService.class;
                          String serviceId = info.getServerId();
                          String serviceType = info.getServerType();
                          String serviceUrl = info.getServerUrl();
                          Properties props = null;
                          runtimeServiceRegister.registService(serviceClass,serviceId,serviceType,serviceUrl,props);*/
                        try {
                            pictureHessianProxy = (PictureService) serviceRepository.getService(PictureService.class, "picture_" + String.valueOf(i));

                        } catch (ServiceException e) {
                            e.printStackTrace();
                            bootUpRegister.initService();
                            try {
                                pictureHessianProxy = (PictureService) serviceRepository.getService(PictureService.class, "picture_" + String.valueOf(i));
                            } catch (ServiceException e1) {
                                e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                            }
                        }
                        if (szTypeIds != null) {
                            tempList = pictureHessianProxy.contentSearchByType(szTypeIds, pictureDir, pageInfo.getPageSize(), pageInfo.getQueryTime() + 1L);
                        } else {
                            tempList = pictureHessianProxy.contentSearchByType(null, pictureDir, pageInfo.getPageSize(), pageInfo.getQueryTime() + 1L);
                        }
                        //tempList = pictureHessianProxy.contentSearchByType(szTypeIds, pictureDir, pageInfo.getPageSize(), pageInfo.getQueryTime()+1L);
                        if (tempList != null) {
                            resultSetPool.getResultSet(request.getSession().getId(), searchId).getList().addAll(tempList);
                        }
                        tempList = null;
                        //serviceNum++;
                    }

                    /**
                     * 修改PageInfo
                     */
                    pageInfo.setClientPage(Long.parseLong(clientPage));
                    pageInfo.setQueryTime(pageInfo.getQueryTime() + 1L);
                    resultSetPool.getResultSet(request.getSession().getId(), searchId).setPageInfo(pageInfo);
                    finalResultSet = resultSetPool.getResultSet(request.getSession().getId(), searchId);
                    List result = finalResultSet.getList();
                    Collections.sort(result, comparator);
                    finalResultSet.setList(result);
                }
            }
        }

        if (finalResultSet.getList() == null || 0 == finalResultSet.getList().size()) {
            return INPUT;
        }
        finalResultSet = resultSetPool.getResultSet(request.getSession().getId(), searchId);
        finalResultSet.getPageInfo().setCurrentPage(Long.parseLong(clientPage));

        long client_page = finalResultSet.getPageInfo().getClientPage();
        List<SzPicture> pictures = new ArrayList<SzPicture>();
        for (long i = (client_page - 1) * pageSize; i < client_page * pageSize; i++) {
            if (i < finalResultSet.getList().size()) {
                pictures.add(finalResultSet.getList().get((int) i));
            } else {
                break;
            }
        }
        translatePictureUrl(pictures);
        resultSet.setList(pictures);
        resultSet.setPageInfo(finalResultSet.getPageInfo());
        resultSet.setKeyWords(fileName);
        resultSet.setActionName("pictureContentSearch");
        resultSet.setType("Picture");
        return SUCCESS;
    }

    /**
     * 修改图片
     *
     * @return success
     */
    public String modifyPicture() throws IOException {
        SzPicture temp = new SzPicture();
        temp.setId(id);
        temp.setTitle(title);
        temp.setNote(note);
        pictureService.modifyPicInfo(temp);
        getResponse().getWriter().print("success");
        return null;
    }

    /**
     * 删除图片
     *
     * @return
     */
    public String deletePicture() {
        pictureService.delete(id);
        return SUCCESS;
    }

    /**
     * 批量删除图片
     *
     * @return
     */
    public String deletePictureList() {
        for (Long id : deleteIds) {
            pictureService.delete(id);
        }
        return SUCCESS;
    }

    /**
     * 显示图片详细信息
     *
     * @return
     */
    public String showDetail() {
        picture = pictureService.findDetail(picture.getId());
        /*String url = fileDownloadAction.getUrl(picture.getServer(), picture.getPictureUrl());
        picture.setPictureUrl(url);*/
        return null != picture ? SUCCESS : ERROR;
    }

    public String getPictureInfo() {
        object = pictureService.findDetail(id);
        actionName = "modifyPicture";
        return null != object ? SUCCESS : INPUT;
    }

    /**
     * 显示同类型图片
     *
     * @return success
     */
    public String showPictureByType() {
        resultSet = pictureService.findByType(pictureTypeId, pageSize, page);
        resultSet.setKeyWords("%");
        return SUCCESS;
    }

    private void translatePictureUrl(List<SzPicture> pictureList){
        for(SzPicture picture : pictureList){
            if(!urlGetter.isNeedTranslate(picture.getMinPictureUrl())){
            picture.setMinPictureUrl(urlGetter.getRemoteUrl(picture.getMinPictureUrl(), picture.getServer()));
            }
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public List<Long> getPictureIds() {
        return pictureIds;
    }

    public void setPictureIds(List<Long> pictureIds) {
        this.pictureIds = pictureIds;
    }

    public List<SzPicture> getSzPictures() {
        return szPictures;
    }

    public void setSzPictures(List<SzPicture> szPictures) {
        this.szPictures = szPictures;
    }

    public PageResultSet<SzPicture> getResultSet() {
        return resultSet;
    }

    public void setResultSet(PageResultSet<SzPicture> resultSet) {
        this.resultSet = resultSet;
    }

    public SzPicture getPicture() {
        return picture;
    }

    public void setPicture(SzPicture picture) {
        this.picture = picture;
    }

    public PictureService getPictureService() {
        return pictureService;
    }

    public void setPictureService(PictureService pictureService) {
        this.pictureService = pictureService;
    }

    public Long getPictureTypeId() {
        return pictureTypeId;
    }

    public void setPictureTypeId(Long pictureTypeId) {
        this.pictureTypeId = pictureTypeId;
    }

    public PictureTypeService getPictureTypeService() {
        return pictureTypeService;
    }

    public void setPictureTypeService(PictureTypeService pictureTypeService) {
        this.pictureTypeService = pictureTypeService;
    }

    public List<Long> getSzTypeIds() {
        return szTypeIds;
    }

    public void setSzTypeIds(List<Long> szTypeIds) {
        this.szTypeIds = szTypeIds;
    }

    public String getFileName() {
        return fileName;
    }

    public SzPicture getObject() {
        return object;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getPageSize() {
        return pageSize;
    }

    public void setPageSize(Long pageSize) {
        this.pageSize = pageSize;
    }

    public Long getPage() {
        return page;
    }

    public void setPage(Long page) {
        this.page = page;
    }

    public String getTemp() {
        return temp;
    }

    public void setTemp(String temp) {
        this.temp = temp;
    }

    public void setServiceRepository(ServiceRepository serviceRepository) {
        this.serviceRepository = serviceRepository;
    }

    public void setPictureHessianProxy(PictureService pictureHessianProxy) {
        this.pictureHessianProxy = pictureHessianProxy;
    }

    public String getSearchId() {
        return searchId;
    }

    public void setSearchId(String searchId) {
        this.searchId = searchId;
    }

    public ResultSetPool getResultSetPool() {
        return resultSetPool;
    }

    public void setResultSetPool(ResultSetPool resultSetPool) {
        this.resultSetPool = resultSetPool;
    }

    public String getClientPage() {
        return clientPage;
    }

    public void setClientPage(String clientPage) {
        this.clientPage = clientPage;
    }

    public String getIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(String isAdmin) {
        this.isAdmin = isAdmin;
    }

    public String getActionName() {
        return actionName;
    }

    public void setFileDownloadAction(FileDownloadAction fileDownloadAction) {
        this.fileDownloadAction = fileDownloadAction;
    }

    public void setDeleteIds(List<Long> deleteIds) {
        this.deleteIds = deleteIds;
    }

    public void setBootUpRegister(BootUpRegister bootUpRegister) {
        this.bootUpRegister = bootUpRegister;
    }

    public void setUrlGetter(UrlGetter urlGetter) {
        this.urlGetter = urlGetter;
    }
}
